package com.pay.channel.adapter;

import com.pay.channel.dto.ChannelRequest;
import com.pay.channel.dto.ChannelResponse;
import com.pay.channel.spi.ChannelAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class AlipayChannelAdapter implements ChannelAdapter {
    
    // 模拟支付宝支付存储，实际项目中应该调用支付宝API
    private static final Map<String, ChannelResponse> alipayTradeStore = new ConcurrentHashMap<>();
    
    @Override
    public String getChannelName() {
        return "ALIPAY";
    }
    
    @Override
    public ChannelResponse pay(ChannelRequest request) {
        log.info("支付宝支付，请求参数：{}", request);
        
        try {
            // 参数校验
            if (request.getOrderNo() == null || request.getOrderNo().trim().isEmpty()) {
                return createErrorResponse("订单号不能为空");
            }
            if (request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
                return createErrorResponse("支付金额不能为空或小于等于0");
            }
            
            // 生成支付宝订单号
            String alipayOrderNo = "ALI" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
            
            // 调用支付宝API（这里模拟）
            ChannelResponse response = new ChannelResponse();
            response.setOrderNo(request.getOrderNo());
            response.setAmount(request.getAmount());
            response.setStatus("PENDING");
            response.setPayUrl("https://openapi.alipay.com/gateway.do?order=" + alipayOrderNo);
            response.setMessage("支付宝支付处理中");
            response.setSuccess(true);
            
            // 保存交易记录
            alipayTradeStore.put(request.getOrderNo(), response);
            
            log.info("支付宝支付发起成功，订单号：{}，支付宝订单号：{}", request.getOrderNo(), alipayOrderNo);
            
            return response;
            
        } catch (Exception e) {
            log.error("支付宝支付失败", e);
            return createErrorResponse("支付宝支付失败：" + e.getMessage());
        }
    }
    
    @Override
    public ChannelResponse query(String orderNo) {
        log.info("支付宝查询，订单号：{}", orderNo);
        
        try {
            // 参数校验
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return createErrorResponse("订单号不能为空");
            }
            
            // 查询本地记录
            ChannelResponse localTrade = alipayTradeStore.get(orderNo);
            if (localTrade == null) {
                return createErrorResponse("订单不存在");
            }
            
            // 调用支付宝查询API（这里模拟）
            String alipayStatus = queryAlipayStatus(orderNo);
            if (alipayStatus != null) {
                localTrade.setStatus(alipayStatus);
                alipayTradeStore.put(orderNo, localTrade);
            }
            
            return localTrade;
            
        } catch (Exception e) {
            log.error("支付宝查询失败", e);
            return createErrorResponse("支付宝查询失败：" + e.getMessage());
        }
    }
    
    @Override
    public ChannelResponse refund(String orderNo, String amount) {
        log.info("支付宝退款，订单号：{}，金额：{}", orderNo, amount);
        
        try {
            // 参数校验
            if (orderNo == null || orderNo.trim().isEmpty()) {
                return createErrorResponse("订单号不能为空");
            }
            if (amount == null || amount.trim().isEmpty()) {
                return createErrorResponse("退款金额不能为空");
            }
            
            BigDecimal refundAmount;
            try {
                refundAmount = new BigDecimal(amount);
                if (refundAmount.compareTo(BigDecimal.ZERO) <= 0) {
                    return createErrorResponse("退款金额必须大于0");
                }
            } catch (NumberFormatException e) {
                return createErrorResponse("退款金额格式不正确");
            }
            
            // 查询原交易
            ChannelResponse originalTrade = alipayTradeStore.get(orderNo);
            if (originalTrade == null) {
                return createErrorResponse("原交易不存在");
            }
            
            // 检查交易状态
            if (!"SUCCESS".equals(originalTrade.getStatus())) {
                return createErrorResponse("原交易状态不正确，无法退款");
            }
            
            // 检查退款金额
            if (refundAmount.compareTo(originalTrade.getAmount()) > 0) {
                return createErrorResponse("退款金额不能大于原交易金额");
            }
            
            // 生成退款订单号
            String refundOrderNo = "ALIREF" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
            
            // 调用支付宝退款API（这里模拟）
            ChannelResponse refundResponse = new ChannelResponse();
            refundResponse.setOrderNo(orderNo);
            refundResponse.setAmount(refundAmount);
            refundResponse.setStatus("PENDING");
            refundResponse.setMessage("支付宝退款处理中");
            refundResponse.setSuccess(true);
            
            // 保存退款记录
            alipayTradeStore.put(refundOrderNo, refundResponse);
            
            log.info("支付宝退款发起成功，退款订单号：{}，原订单号：{}", refundOrderNo, orderNo);
            
            return refundResponse;
            
        } catch (Exception e) {
            log.error("支付宝退款失败", e);
            return createErrorResponse("支付宝退款失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建错误响应
     */
    private ChannelResponse createErrorResponse(String message) {
        ChannelResponse response = new ChannelResponse();
        response.setMessage(message);
        response.setSuccess(false);
        return response;
    }
    
    /**
     * 查询支付宝支付状态（模拟）
     */
    private String queryAlipayStatus(String orderNo) {
        // 模拟查询支付宝支付状态
        // 实际项目中应该调用支付宝查询API
        if (orderNo.startsWith("ALI")) {
            // 模拟85%的概率支付成功
            if (Math.random() < 0.85) {
                return "SUCCESS";
            } else {
                return "FAILED";
            }
        }
        return null;
    }
}



